package com.zan.twolevel.level1;

import com.zan.twolevel.ListNode;

/**
 * @Author Zan
 * @Date 2023/12/3 19:34
 * @Description : 反转链表 By 虚拟节点 or 无虚拟节点
 */
public class ReverseList {

    public static void main(String[] args) {
        ListNode head = init();
        System.out.println(head);
        ListNode node = reverseListNode(head);
        System.out.println(node);
    }

    /**
     * 反转链表 - 通过虚拟节点
     * @param head
     * @return
     */
    public static ListNode reverseListNode(ListNode head) {
        // 创建虚拟节点
        ListNode dummyNode = new ListNode();
        ListNode oldNode = head;
        while (oldNode != null) {
            ListNode next = oldNode.next;
            // 获取到的
            oldNode.next = dummyNode.next;
            dummyNode.next = oldNode;
            oldNode = next;
        }
        return dummyNode.next;
    }

    /**
     * 初始化链表
     */
    public static ListNode init() {
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);
        ListNode l4 = new ListNode(4);
        ListNode l5 = new ListNode(5);
        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l5;
        return l1;
    }
}
